//
//  COCallGiftView.swift
//  CocoProject
//
//  Created by Vill on 2023/11/15.
//

import UIKit

class COCallGiftView: UIView,UITableViewDataSource, UITableViewDelegate {

    private var gifts = [COGiftContent]()
    private var timer: Timer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        isHidden = true
        addSubview(tableView)
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: -- Property
    lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect(x: 0, y: 0, width: self.width, height: self.height))
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.rowHeight = 85
        view.estimatedRowHeight = 85
        view.separatorStyle = .none
        view.register(COCallGiftTableCell.self, forCellReuseIdentifier: "COCallGiftTableCell")
        return view
    }()
    
    func show(gift: COGiftContent) {
        self.isHidden = false
        tableView.alpha = 1
        gifts.append(gift)
        tableView.beginUpdates()
        tableView.insertRows(at: [IndexPath(row: gifts.count-1, section: 0)], with: .left)
        tableView.endUpdates()
        tableView.scrollToRow(at: IndexPath(row: gifts.count-1, section: 0), at: .bottom, animated: true)
        addTimer()
    }

    private func addTimer() {
        if timer != nil {
            removeTimer()
        }
        timer = Timer(timeInterval: 2.5, target: self, selector: #selector(timerRun), userInfo: nil, repeats: false)
        RunLoop.current.add(timer!, forMode: .common)
    }
    
    @objc private func timerRun() {
        UIView.animate(withDuration: 0.3) {
            self.tableView.alpha = 0
        } completion: { (completion) in
            self.isHidden = true
            self.gifts.removeAll()
            self.tableView.reloadData()
        }
    }
    
    private func removeTimer() {
        timer?.invalidate()
        timer = nil
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return gifts.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "COCallGiftTableCell", for: indexPath) as! COCallGiftTableCell
        cell.gift = gifts[indexPath.row]
        return cell
    }
    
    
}
